﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using SAP.WebServices;
using System.Collections;
using System.Globalization;
using SAP.Admin.DAO;
using ReadXMLFile;

namespace SAP
{
    public partial class MyRequest : System.Web.UI.Page
    {
        private LoginSession CurrentLoginSession;
        private GeneralFunctions GF;
        public static DataSet ds = new DataSet();
        //private static string FromDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM/dd/yyyy");
        //private static string ToDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)).ToString("MM/dd/yyyy");
        private DateTime FromDate;
        private DateTime ToDate;
        private int rqStatus = -1;
        private int EmpID = -1;

        protected void Page_Load(object sender, EventArgs e)
        {
            //lvStage.Items[0].Visible = false;
            //1. Neu la manager: show menu Emp's requisition
            //2. Neu approval mode: + show approve link
            //                      
            //                      + show all requisition cua emp cua manager nay
            SessionCheck();
            
            GetDefault df = new GetDefault();
            DataTable dt = new DataTable();
            dt = df.GetLoginInfo(CurrentLoginSession.UserName, 0).Tables[0];
            EmpID = (int)dt.Rows[0]["EmpID"];
           
            rqStatus = Int32.Parse(ddlType.SelectedValue.ToString());
            if (!IsPostBack)
            {

                FromDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                ToDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month));
                txtFromDate.Text = FromDate.ToString("dd/MM/yyyy"); ;
                txtToDate.Text = ToDate.ToString("dd/MM/yyyy"); ;
                
                lvStage.DataBind();
                loadData();
                //loadRole();
            }
            
        }

        private void loadRole() {
            
            ArrayList param = new ArrayList();
            param.Add("@UserName");
            ArrayList vals = new ArrayList();
            vals.Add(User.Identity.Name);
            DataTable tb = GF.ObjectSelect("usp_Users_GetRole", param, vals);
            if (tb.Rows.Count > 0) {
                string role = tb.Rows[0]["RoleName"].ToString();
                if (role.Equals("manager"))
                {

                }
                else {
 
                }
            }
        }
        protected void OnLayoutCreated(object sender, EventArgs e)
        {
            //lvStage.FindControl("StatusName").Visible = false;
             
        }
        static DataTable dtMain;
        private void loadData()
        {

            String sqlStr = "";

            rqStatus = Int32.Parse(ddlType.SelectedValue.ToString());
            if (rqStatus == -1)
                sqlStr = "select * from OffHeader where EmpID = " + EmpID;// + " AND ReqType <> 'E'";
            else
                sqlStr = "select * from OffHeader where EmpID = " + EmpID + " AND Status = " + rqStatus;// +" AND ReqType <> 'E'";

            sqlStr = sqlStr + " AND ReqDate >= '" + FromDate.ToString("yyyy-MM-dd") + "' AND ReqDate <= '" + ToDate.ToString("yyyy-MM-dd")+ "'";
            dtMain = GF.RunQuery(sqlStr);
            lvStage.DataSource = dtMain;
            lvStage.DataBind();
        }
       
        protected void ProductListPagerCombo_PreRender(object sender, EventArgs e)
        {
            //Binding();
        }

        protected void lvStage_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            { 
                if (ds == null)
                    return;
                int i_idx = e.Item.DataItemIndex;
            
                if (e.CommandName == "Submit") 
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "ShowLoading", "Dialog.showLoader();", true);

                    int reqIdSubmited = Int32.Parse(dtMain.Rows[i_idx]["hdrID"].ToString());// Int32.Parse(dr["ReqID"].ToString());
                    ArrayList param = new ArrayList();
                    param.Add("@hdrID");
                    ArrayList vals = new ArrayList();
                    vals.Add(reqIdSubmited);
                    GF.ObjectUpdate("usp_OffHeader_Submit", param, vals);
                
                    if (CurrentLoginSession.ManagerEmail != "")
                    {
                        Emailling omail = new Emailling();                      
                        omail.SendMailNow(CurrentLoginSession.ManagerEmail, "Stock Requisition has been escalated for your approval", omail.GetTemplate_Submit(reqIdSubmited));
                    }
                    ib_Filter_Click(null, null);

                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                           "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }

        protected void lvAll_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            //if (e.CommandName == "View")
            //{
            //    LinkButton lb = (LinkButton)e.CommandSource;
            //    Response.Redirect("/TimeSheet/ABEO_TIMESHEET.aspx?clgCode=" + lb.CommandArgument);
            //}
        }

        protected void lvStage_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            //this.lvStage.EditIndex = e.NewEditIndex;
            //DataView dv = new DataView(ds.Tables[0]);
            //this.lvStage.DataSource = dv;
            //this.lvStage.DataBind();
        }

        protected void btnNewEntry_Click(object sender, EventArgs e)
        {
            Response.Redirect("TimeEntry.aspx");
        }

        protected void btnFilterMyTS_Click(object sender, EventArgs e)
        {
           
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            base.OnLoadComplete(e);
            if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
            {

                switch (this.Request["__EVENTARGUMENT"].ToString())
                {
                    case "EditItemCallBack":
                        break;
                }
            }
            //SetForm();
        }

        private void SetForm()
        {

            for(int i = 0; i < lvStage.Items.Count ; i++)
            {
                ListViewItem lvi = lvStage.Items[i];
                if (ds.Tables[0].Rows[i]["PrjCode"].ToString().Equals(""))
                {
                    lvi.Controls.Remove((LinkButton)lvi.FindControl("imgbEdit"));
                    lvi.Controls.Remove((LinkButton)lvi.FindControl("imgbDelete"));
                    int idx = lvi.Controls.IndexOf((Label)lvi.FindControl("Date"));
                    lvi.Controls.Remove((Label)lvi.FindControl("Date"));
                    ((Label)lvi.FindControl("Hour")).Font.Bold = true;
                    Label lblTotal = new Label();
                    lblTotal.ID = "lblTotal"+ i.ToString();
                    if(i == lvStage.Items.Count - 1)
                        lblTotal.Text = "Grand Total:";
                    else
                        lblTotal.Text = "Total:";
                    lblTotal.Font.Bold = true;
                    lvi.Controls.AddAt(idx, lblTotal);
                }
            }
        }

        protected void ib_Filter_Click(object sender, ImageClickEventArgs e)
        {
            CultureInfo ivC = new System.Globalization.CultureInfo("es-US");

            //FromDate = Convert.ToDateTime(txtFromDate.Text, ivC);
            //ToDate = Convert.ToDateTime(txtToDate.Text, ivC);

            FromDate = DateTime.ParseExact(txtFromDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            ToDate = DateTime.ParseExact(txtToDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

            rqStatus = Int32.Parse(ddlType.SelectedValue.ToString());
            loadData();
        }

        public void SessionCheck()
        {

            if (Session["LoginSession"] != null)
            {
                this.CurrentLoginSession = (LoginSession)Session["LoginSession"];
                GF = new GeneralFunctions(CurrentLoginSession.UserName);
            }
            else
            {
                Response.Redirect("SessionErrorPage.aspx");
            }

        }    
    }
}
/*
ReqType
Requester
ReqName
TaxDate
DocDate
DocDueDate
Comments
JrnlMemo
slpcode
OwnerCode
TrnspCode
Address
Address2
Project
LicTradNum
NumAtCard
GroupNum
ReqDate
Indicator
ImportEnt
Filler
U_UserID
ObjType
     */